package com.yale.elasticsearch.service.aggregation;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.*;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;

import lombok.experimental.var;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author :yale
 * @date : 2024/7/31
 */
@Slf4j
@Service
public class AggrBucketMetricService {

    @Resource
    private ElasticsearchClient elasticsearchClient;

    /**
     * topHits 按照员工岁数分桶、然后统计每个岁数员工工资最高值
     */
    public String aggregationTopHits() {
        String responseResult = "";
        try {
            // Create the top hits aggregation
            Aggregation topHitsAgg = Aggregation.of(a -> a.topHits(th -> th
                    .size(1)
                    .sort(so -> so
                            .field(f -> f
                                    .field("salary")
                                    .order(SortOrder.Desc)
                            )
                    )
            ));

            // 创建一个Terms聚合，用于按年龄分桶
            Aggregation ageTermsAgg = Aggregation.of(a -> a.terms(t -> t
                    .field("age")
                    .size(100)
            ).aggregations("top_salary", topHitsAgg));


            // 创建搜索请求，指定索引和聚合
            SearchRequest searchRequest = SearchRequest.of(s -> s
                    .index("employee")
                    .size(0) // 不返回文档，只返回聚合结果
                    .aggregations("by_age", ageTermsAgg)
            );

            SearchResponse<Map> response = elasticsearchClient.search(searchRequest, Map.class);

            // Extract and process the aggregations from the response
            Aggregate aggregate =  response.aggregations().get("by_age");
            if (aggregate != null) {

//                var termsAggResult = (Map<String, Object>) aggregations.get("salary_bucket");
//                if (termsAggResult != null) {
//                    List<Map<String, Object>> buckets = (List<Map<String, Object>>) termsAggResult.get("buckets");
//                    if (buckets != null) {
//                        System.out.println("-------------------------------------------");
//                        System.out.println("Aggregation Information:");
//                        for (Map<String, Object> bucket : buckets) {
//                            System.out.println("Bucket Name: " + bucket.get("key"));
//                            var topHits = (Map<String, Object>) bucket.get("salary_max_user");
//
//                            if (topHits != null) {
//                                List<Map<String, Object>> hits = (List<Map<String, Object>>) topHits.get("hits");
//                                for (Map<String, Object> hit : hits) {
//                                    System.out.println(hit);
//                                }
//                            }
//                        }
//                        System.out.println("-------------------------------------------");
//                    }
//                }
                responseResult = response.toString();
            }
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
        return responseResult;
    }

}
